package com.jframe.sys.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

public class IOUtil {
	
	public static File mkDir(String path, String dirName) {
		try {
			
			if ("".equals(path) && "".equals(dirName)) {
				return null;
			}
			File dir = new File(path + "\\" + dirName + "\\");
			if (!dir.exists()) {
				dir.mkdir();
			}
			return dir;

		} catch (Exception ex) {
			return null;
		}
	}

	public static File mkDir(String dir) {
		File newdir = new File(dir);
		if (!newdir.exists()) {
			newdir.mkdir();
		}
		return newdir;

	}

	public static File mkDirs(String dir) {
		File newdir = new File(dir);
		if (!newdir.exists()) {
			newdir.mkdirs();
		}
		return newdir;
	}

	/**
	 * 创建文件
	 * 
	 * @param dir 文件目录
	 * @param FileName 文件名
	 * @return 创建的文件.
	 */
	public static File createFile(File dir, String FileName) {
		try {
			File tempFile = new File(dir, FileName);
			if (tempFile.exists()) {
				tempFile.delete();
			}
			tempFile.createNewFile();
			return tempFile;
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * �����ļ�������ļ�������ɾ��
	 * 
	 * @param fileURL
	 *            String
	 * @return File
	 */
	public static File createFile(String fileURL) {
		try {
			File tempFile = new File(fileURL);
			if (tempFile.exists()) {
				tempFile.delete();
			}
			tempFile.createNewFile();
			return tempFile;
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * �ļ�ɾ��
	 * 
	 * @param fileURL
	 *            String
	 * @return boolean
	 */
	public static boolean delFile(String fileURL) {
		try {
			File tempFile = new File(fileURL);
			if (tempFile.exists()) {
				tempFile.delete();
			}
			return true;
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * ���ָ�����ļ����ļ�·���������ļ����ݡ�
	 * 
	 * @param fileName
	 *            String
	 * @return String
	 */
	public static String readFile(String fileName) {
		String fileContent = "";
		try {
			File f = new File(fileName);
			if (f.isFile() && f.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(f), "utf-8");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {
					fileContent += line + "\r\n";
				}
				read.close();
			}
		} catch (Exception e) {
			System.out.println("读取文件内容操作出错");
			e.printStackTrace();
		}
		return fileContent;

	}

	/**
	 * ��ָ���ļ�����д��ָ�����ļ���
	 * 
	 * @param dir
	 *            File �ļ�Ŀ¼��
	 * @param fileName
	 *            String �ļ����
	 * @param fileContent
	 *            String �ļ�����
	 * @return boolean
	 */
	public static boolean writeFile(File dir, String fileName,
			String fileContent) {
		try {
			File file = createFile(dir, fileName);
			RandomAccessFile fw = new RandomAccessFile(file, "rw");
			fw.writeBytes(fileContent);
			fw.close();
			return true;
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * ��ָ���ļ�����д��ָ�����ļ�������ʹ�ñ�������
	 * 
	 * @param path
	 *            String ·��
	 * @param fileName
	 *            String �ļ���
	 * @param fileContent
	 *            String �ļ�����
	 * @return boolean
	 */
	public static boolean writeFile(String path, String fileName,
			String fileContent) {
		try {
			File dir = mkDir(path);
			return writeFile(dir, fileName, fileContent);
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * ��ָ��������д��ָ�����ļ�
	 * 
	 * @param fileURL
	 *            String �ļ���ַ�����ļ����·����
	 * @param fileContent
	 *            String �ļ����ݡ�
	 * @return boolean
	 */

	public static boolean writeFile(String fileURL, String fileContent) {
		try {
			int separatorIndex =  fileURL.lastIndexOf("/") > fileURL.lastIndexOf("\\") ? fileURL.lastIndexOf("/"):fileURL.lastIndexOf("\\");
			String path = fileURL.substring(0, separatorIndex);
			IOUtil.mkDirs(path); //makeDirs(path);
			File file = createFile(fileURL);
			RandomAccessFile fw = new RandomAccessFile(file, "rw");
			fw.write(fileContent.getBytes("utf-8"));
			fw.close();
			return true;

		} catch (Exception ex) {
			return false;
		}
	}

	
	public static boolean FileWrite(String fileURL, String fileContent) {
		try {
			File file = createFile(fileURL);
			FileWriter fw = new FileWriter(file);
			fw.write(fileContent);
			fw.close();

			return true;

		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * ������ƣ�getFileName �����ܣ�ȡ���ļ���ȥ��·����)չ��
	 * 
	 * @param fullFileName
	 *            ԭ�ļ���
	 * @return ȡ������ļ���
	 */
	public static String getFileName(String fullFileName) {
		try {
			if (fullFileName == null) {
				return "";
			}
			int i;
			String resultStr = "";
			for (i = fullFileName.length() - 1; i >= 0; i--) {

				// �����linux��Ŀ¼���ļ����/������NT����\������}�����Ҫ�ж�
				if (fullFileName.substring(i, i + 1).equals("\\")
						|| fullFileName.substring(i, i + 1).equals("/")) {
					break;
				}
			}
			if (i >= 0) // ȥ��·������
			{
				resultStr = fullFileName
						.substring(i + 1, fullFileName.length());
			} else {
				resultStr = fullFileName;
			}
			for (i = resultStr.length() - 1; i >= 0; i--) {
				if (resultStr.substring(i, i + 1).equals(".")) {
					break;
				}
			}
			if (i >= 0) // ȥ��)չ��
			{
				resultStr = resultStr.substring(0, i);
			}
			return resultStr;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * ������ƣ�getFileType �����ܣ�ȡ���ļ���)չ��ȥ��·�����ļ���
	 * 
	 * @param fullFileName
	 *            ԭ�ļ���
	 * @return ȡ�����)չ��
	 */
	public static String getFileType(String fullFileName) {
		try {
			if (fullFileName == null) {
				return "";
			}
			int i;
			for (i = fullFileName.length() - 1; i >= 0; i--) {
				if (fullFileName.substring(i, i + 1).equals(".")) {
					break;
				}
				if (fullFileName.substring(i, i + 1).equals("\\")
						|| fullFileName.substring(i, i + 1).equals("/")) {
					return "";
				}
			}
			if (i >= 0) 
			{
				return fullFileName.substring(i + 1, fullFileName.length());
			} else {
				return "";
			}
		} catch (Exception e) {
			return "";
		}
	}



	/**
	 * 获取指定目录下的文件列表
	 * 
	 * @param path
	 *            ���·��(������˵�)
	 * @return ����,�����ļ���
	 */
	public static String[] getFileList(String path) {
		return getFileList(path, "*.*");
	}

	/**
	 * ������ƣ�getFileList �����ܣ�����ĳһ��Ŀ¼���ĳ��)չ��������ļ�
	 * 
	 * @param path
	 *            ���·��(������˵�)
	 * @param str
	 *            Ҫ���ҵ��ַ�(��*.txt,a*b.*��)
	 * @return ����,���ҵ����ļ���
	 */
	public static String[] getFileList(String path, String str) {
		File file = new File(path);	
		MyFilter mf = new MyFilter(str);
		String[] fileList = file.list(mf);
		return fileList;
	}

	/**
	 * ������ظ����ļ���
	 * 
	 * @param postfix
	 *            String �ļ���׺��
	 * @return String
	 */
	public static String getRandomFileName(String postfix) {
		try {
			long now = System.currentTimeMillis();
			String prefix = String.valueOf(now);
			String fileName = prefix + "." + postfix;
			return fileName;
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * ����ȡ�ļ���ǰ׺��
	 * 
	 * @return String
	 */
	public static String getRandomFileName() {
		try {
			long now = System.currentTimeMillis();
			String prefix = String.valueOf(now);
			return prefix;
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 返回指定文件的大小 ,单位k
	 * 
	 * @param path
	 * @return
	 */
	public static long getSize(String path) {

		File file = new File(path);
		return file.length() / 1024;
	}
	public static boolean copyFile(String oldFileName, String newFileName) {
		try {
			FileInputStream is = new FileInputStream(oldFileName);
			byte[] temps = new byte[is.available()];
			is.read(temps);
			FileOutputStream os = new FileOutputStream(newFileName);
			os.write(temps);
			is.close();
			os.close();
			return true;
		} catch (Exception e) {

			return false;
		}
	}
	/**
	 * 判断一个路径是否是目录，如果是目录返回true,否则返回false
	 * @param path
	 * @return
	 */
	public static boolean isDir(String path){
		
		File file = new File(path);
		if(file.exists()){
			
			return file.isDirectory();
		}
		else{
			return false;
		}
	}
	/**
	 * 判断一个路径是否是文件，如果是文件则返回true,否则返回false
	 * @param path
	 * @return
	 */
	public static boolean isFile(String path){
		File file = new File(path);
		if(file.exists()){
			return file.isFile();
		}
		else{
			return false;
		}
	}
	
    /**
     * 目录copy
     * @param srcDir 源目录
     * @param toDir 目标目录
     * @return
     */
	public static boolean copyDir(String srcDir, String toDir) {
		
		mkDirs(toDir); //再创建目录
		File[] files;
		File file = new File(srcDir);
		if ((file.exists()) ){
			if(file.isDirectory()) {
				files = file.listFiles();
				if (files != null) {
					for (int i = 0; i < files.length; ++i) {
						if (files[i].exists()){
							if (files[i].isDirectory()){
								String toPath =  toDir + File.separator + files[i].getName();
								//ExtendIO.mkDirs(toPath); //makeDirs(toPath);
								copyDir(files[i].getPath(),toPath);
							  }
							else if (files[i].isFile()) {
								String toPath =  toDir + File.separator + files[i].getName();
								copyFile(files[i].getPath(), toPath);
							}
						}
					}
				}
			}
			else if(file.isFile()){
				copyFile(srcDir,toDir); //做文件copy
			}
		} else {
			//System.out.println("srcDir not exists or is not directory!");
			return false;
		}
		//System.out.println("copy directory form:" + srcDir + " to :" + toDir
			//	+ ".");
		return true;
	}
	
	/**
	 * 将windows形式的路径转换成Unix形式路径，这样更为通用
	 * @param path
	 * @return
	 */
	public static String winPath2UnixPath(String path){
		
		return StringUtil.replaceAll(path, "\\", "/");
	}
	
	/**   
     * 删除文件，可以是单个文件或文件夹   
     * @param   fileName    待删除的文件名   
     * @return 文件删除成功返回true,否则返回false   
     */   
    public static boolean delete(String fileName){    
        File file = new File(fileName);    
        if(!file.exists()){    
            System.out.println("删除文件失败："+fileName+"文件不存在");    
            return false;    
        }else{    
            if(file.isFile()){    
                    
                return deleteFile(fileName);    
            }else{    
                return delDirectory(fileName);    
            }    
        }    
    }    
        
    /**   
     * 删除单个文件   
     * @param   fileName    被删除文件的文件名   
     * @return 单个文件删除成功返回true,否则返回false   
     */   
    public static boolean deleteFile(String fileName){    
        File file = new File(fileName);    
        if(file.isFile() && file.exists()){    
            file.delete();    
            //System.out.println("删除单个文件"+fileName+"成功！");    
            return true;    
        }else{    
           // System.out.println("删除单个文件"+fileName+"失败！");    
            return false;    
        }    
    }    
    /**
     * 判断指定目录是否有子文件
     * @param path
     * @return
     */
    public static boolean hasSubDirOrFile(String path){
    	
    	 File dirFile = new File(path);  
    	 if(!dirFile.exists() || !dirFile.isDirectory()){    
             System.out.println( path+"目录不存在！");    
             return false;    
         }  
    	 File[] files = dirFile.listFiles(); 
    	 return files!=null && files.length > 0 ? true :false;
    }
    /**   
     * 删除目录（文件夹）以及目录下的文件   
     * @param   dir 被删除目录的文件路径   
     * @return  目录删除成功返回true,否则返回false   
     */   
    public static boolean delDirectory(String dir){    
        //如果dir不以文件分隔符结尾，自动添加文件分隔符    
        if(!dir.endsWith(File.separator)){    
            dir = dir+File.separator;    
        }    
        File dirFile = new File(dir);    
        //如果dir对应的文件不存在，或者不是一个目录，则退出    
        if(!dirFile.exists() || !dirFile.isDirectory()){    
            System.out.println("删除目录失败"+dir+"目录不存在！");    
            return false;    
        }    
        boolean flag = true;    
        //删除文件夹下的所有文件(包括子目录)    
        File[] files = dirFile.listFiles();    
        for(int i=0;i<files.length;i++){    
            //删除子文件    
            if(files[i].isFile()){    
                flag = deleteFile(files[i].getAbsolutePath());    
                if(!flag){    
                    break;    
                }    
            }    
            //删除子目录    
            else{    
                flag = delDirectory(files[i].getAbsolutePath());    
                if(!flag){    
                    break;    
                }    
            }    
        }    
            
        if(!flag){    
            System.out.println("删除目录失败");    
            return false;    
        }    
            
        //删除当前目录    
        if(dirFile.delete()){    
            System.out.println("删除目录"+dir+"成功！");    
            return true;    
        }else{    
            System.out.println("删除目录"+dir+"失败！");    
            return false;    
        }    
    }  
	
	public static void main(String args[]){
		
		String TEMPLATE_PATH = "webRoot\\"  + "template" + File.separator;
		String PLAY_PATH = "webRoot\\" + "play" + File.separator;
		String ZQBB_PATH = PLAY_PATH + "zqbb" + File.separator;
		
		String localPath = ZQBB_PATH.substring(0, ZQBB_PATH.lastIndexOf(File.separator));
		String folderName = localPath.substring(localPath.lastIndexOf(File.separator) + 1);
		String folderPath = localPath.substring(0, localPath.lastIndexOf(File.separator));
		      
		System.out.println(localPath);
		System.out.println(folderName);
		System.out.println(folderPath);

	}

}

class MyFilter implements FilenameFilter {
	private String con1 = "";

	public MyFilter() {
	}

	public MyFilter(String str) {
		con1 = str;
	}

	public boolean accept(File dir, String fileName) {
		boolean bAccept;
		if (con1.equals("")) {
			bAccept = fileName.toLowerCase().endsWith(".di");
		} else if (WildcardMatcher.match(fileName, con1, true)) {
			bAccept = true;
		} else {
			bAccept = false;
		}
		return bAccept;
	}
}
